const {
	Service
} = require('uni-cloud-router')
const uniID = require("uni-id");
module.exports = class WorkService extends Service {
	async add(post,uid) {
		const db = uniCloud.database();
		const {isAudit} = post[0];
		post.forEach(ele=>{
			ele.createTime=new Date()
			ele.createId=uid
			ele.isDelFlag=0
			ele.status=0 //审核状态默认为待审核
			ele.type=ele.addType+''
			ele.addType=undefined
			ele.isAudit=undefined
			ele.workTime=undefined
		})
		console.log('post', post)
		let res = await db.collection('t_work').add(post)
		//根据word_id添加审核记录，初始默认添加两条待审核记录
		let auditArr = []
		//审核流程提交逻辑（加班记录录入不走这逻辑）
		if(res.inserted==1&&isAudit=='Y'){
			res.ids.forEach((item,index)=>{
				auditArr.push({
					workId:item,
					reason:'',
					status:'2',
					createId:uid,
					auditId:post[index].adminId,
					createTime:new Date(),
					updateTime:new Date(),
					updateId:uid
				})
				auditArr.push({
					workId:item,
					reason:'',
					status:'2',
					createId:uid,
					auditId:post[index].chargeId,
					createTime:new Date(),
					updateTime:new Date(),
					updateId:uid
				})
			})
			let auditRes = await db.collection('t_audit').add(auditArr)
		}
		//返回数据给客户端
		if (res.ids.length>0) {
		    return {code: 0, msg: '录入成功'}  
		} else {  
		    return {code: 1, msg: '录入失败'}  
		}  
		
	}
	//删除调休记录函数
	async del(post) {
		//event为客户端上传的参数
		console.log('post', post)
		const db = uniCloud.database();
		let res = await db.collection('t_work').doc(post.id)
		.update({
			'isDelFlag':1
		});
		console.log(res)
		//返回数据给客户端
		if (res.affectedDocs) {
		    return {code: 0, msg: '删除成功'}  
		} else {  
		    return {code: 1, msg: '删除失败'}  
		}  
		
	}
	//调休/加班记录列表
	async getWorkList(post) {
		const db = uniCloud.database();
		const { page,size,type,uid } = post;
		const pageIndex = page ? page : 1 ;
		const pageSize = size ? size : 1 ;
		const countResult = await db.collection('t_work').where({empId:uid,type:type+'',isDelFlag:0}).count()  //获取集合中的总记录数
		const total = countResult.total  //得到总记录数 
		const totalPage = Math.ceil(total / pageSize)  //计算页数
		var hasMore;  //提示前端是否还有数据
		if (pageIndex > totalPage || pageIndex == totalPage) {  //如果没有数据了，就返回false
			hasMore = false 
		} else {
			hasMore = true 
	   }
		let userData = await db.collection('uni-id-users').where({_id:uid}).field({ 'username': true, }).get()
		let userName=userData.data[0].username
		let res = await db.collection('t_work').where({empId:uid,type:type+'',isDelFlag:0}).orderBy("workTimeStart", "asc").skip((pageIndex - 1) * pageSize).limit(pageSize).get()
		console.log(res)
		//返回数据给客户端
		if (res.affectedDocs>=0) {
		    return {code: 0,data:res.data,userName:userName,hasMore:hasMore, msg: '获取成功'}  
		} else {  
		    return {code: 1, msg: '获取失败'}  
		}  
		
	}
	/**
	 * 获取加班/调休申请列表
	 * @param {String} uid 员工id
	 * @param {number} type 0:调休 ，1:加班"
	 */
	async getApplyList(post) {
		const db = uniCloud.database();
		const { page, size, uid, type } = post;
		const pageIndex = page ? page : 1 ;
		const pageSize = size ? size : 1 ;
		
		// 获取集合中的总记录数
		const countResult = await db.collection('t_work').where({empId: uid, type: type+'', isDelFlag: 0}).count();
		// 得到总记录数 
		const total = countResult.total;
		//计算页数
		const totalPage = Math.ceil(total / pageSize);
		//提示前端是否还有数据
		let hasMore = false;
		//如果没有数据了，就返回false
		if (pageIndex > totalPage || pageIndex == totalPage) {
			hasMore = false;
		} else {
			hasMore = true;
		}
		
		const applyList = await db.collection('t_work')
		.aggregate()
		.lookup({
			from: 'uni-id-users',
			localField: 'empId',
			foreignField: '_id',
			as: 'userInfo'
		})
		.match({
			empId: uid,
			type: type,
			isDelFlag: 0
		})
		.project({
			'userInfo.avatar': true,
			empId: true,
			empName: true,
			status: true,
			workTimeStart: true,
			workDays: true,
			reason: true
		})
		.sort({
			workTimeStart: -1
		})
		.skip((pageIndex - 1) * pageSize)
		.limit(pageSize)
		.end()
		
		// 返回数据给客户端
		if (applyList.affectedDocs >= 0) {
			return {code: 0, data: applyList.data, hasMore: hasMore, msg: '获取成功'}
		} else {
			return {code: 1, msg: '获取失败'}
		}
	}
	// 获取加班和调休记录		//0调休  1加班
	async getWorkReleaxLength(post) {
		const db = uniCloud.database();
		const { uid } = post;
		
		// 加班天数
		let workTotal = 0;
		// 调休天数
		let releaxTotal = 0;
		
		// 查询加班/调休记录列表
		const workResult = await db.collection('t_work').field({ workDays: true, type: true}).where({empId: uid, isDelFlag: 0}).get();
		
		workResult.data.forEach(item => {
			if(item.type === '0') {
				releaxTotal += Number(item.workDays);
			} else if(item.type === '1') {
				workTotal += Number(item.workDays);
			}
		})
		
		let res = {
			data:{
				workTotal,
				releaxTotal
			}
		}
		//返回数据给客户端
		if (workTotal>=0) {
		    return {code: 0,data:res.data, msg: '获取成功'}  
		} else {
			return {code: 1, msg: '获取失败'}
		}
	}
	/**
	 * 获取需要审核加班/调休申请数量
	 * @param {String} uid 审核人员id
	 * @param {number} type 0:调休 ，1:加班"
	 */
	async getWorkApplyCount(post) {
		const db = uniCloud.database();
		const { uid, type } = post;
		
		const countResult = await db.collection('t_work').where({chargeId: uid,type: type + '', status: '0', isDelFlag: 0}).count();
		
		if (countResult.total >= 0) {
			return {code: 0, total: countResult.total, msg: '获取成功'}
		} else {
			return {code: 1, msg: '获取失败'}
		}
	}
	/**
	 * 获取需要审核加班/调休申请列表
	 * @param {String} uid 审核人员id
	 * @param {String} type 0:调休 ，1:加班"
	 */
	async getWorkApplyList(post) {
		const db = uniCloud.database();
		const { uid, type } = post;
		
		const applyList = await db.collection('t_work')
		.aggregate()
		.lookup({
			from: 'uni-id-users',
			localField: 'empId',
			foreignField: '_id',
			as: 'userInfo'
		})
		.match({
			chargeId: uid,
			type: type,
			status: '0',
			isDelFlag: 0
		})
		.project({
			'userInfo.avatar': true,
			empId: true,
			empName: true,
			status: true,
			workTimeStart: true,
			workDays: true,
			reason: true
		})
		.sort({
			workTimeStart: -1
		})
		.end()
		
		// 返回数据给客户端
		if (applyList.affectedDocs >= 0) {
			return {code: 0, data: applyList.data, msg: '获取成功'}
		} else {
			return {code: 1, msg: '获取失败'}
		}
	}
	/**
	 * 获取申请详情
	 * @param {String} workId 申请id
	 */
	async getApplyDetail(post) {
		const db = uniCloud.database();
		const { workId } = post;
		
		const applyDetail = await db.collection('t_audit')
		.aggregate()
		.lookup({
			from: 'uni-id-users',
			localField: 'auditId',
			foreignField: '_id',
			as: 'auditorInfo'
		})
		.match({
			workId: workId
		})
		.project({
			'auditorInfo._id': true,
			'auditorInfo.username': true,
			'auditorInfo.avatar': true,
			status: true,
			reason: true,
			createTime: true
		})
		.sort({
			createTime: -1
		})
		.end()
		
		// 返回数据给客户端
		if (applyDetail.affectedDocs >= 0) {
			return {code: 0, data: applyDetail.data, msg: '获取成功'}
		} else {
			return {code: 1, msg: '获取失败'}
		}
	}
	/**
	 * 更新申请项目负责人
	 * @param {String} workId 申请id
	 * @param {String} chargeId 项目负责人id
	 */
	async updateApplyCharge(post) {
		const db = uniCloud.database();
		const { workId, chargeId } = post;
		
		let res = await db.collection('t_work')
		.doc(workId)
		.update({
			'chargeId': chargeId
		});
		
		//返回数据给客户端
		if (res.affectedDocs) {
			return {code: 0, msg: '撤回成功'}
		} else {
			return {code: 1, msg: '撤回失败'}
		}
	}
	/**
	 * 更新申请审核状态
	 * @param {String} workId 申请id
	 * @param {String} status 审核状态 0:待审核 ，1:已审核 ，2:已失效
	 */
	async updateApplyStatus(post) {
		const db = uniCloud.database();
		const { workId, status } = post;
		
		let res = await db.collection('t_work')
		.doc(workId)
		.update({
			'status': status
		});
		
		//返回数据给客户端
		if (res.affectedDocs) {
			return {code: 0, msg: '处理成功'}
		} else {
			return {code: 1, msg: '处理失败'}
		}
	}
	/**
	 * 更新审核记录审核状态
	 * @param {String} _id 审核记录id
	 * @param {String} status 审核状态 0:已通过 ，1:已拒绝 ,2:待审核
	 * @param {String} reason 拒绝原因
	 */
	async updateApplyAuditStatus(post) {
		const db = uniCloud.database();
		const { _id, reason, status } = post;
		let updateParams = {
			'status': status
		}
		
		// 状态为拒绝时，需添加拒绝理由字段
		if(status === '1') {
			Object.assign(updateParams, {'reason': reason});
		}
		
		let res = await db.collection('t_audit')
		.doc(_id)
		.update(updateParams);
		
		//返回数据给客户端
		if (res.affectedDocs) {
			return {code: 0, msg: '处理成功'}
		} else {
			return {code: 1, msg: '处理失败'}
		}
	}
}
